package com.eystar.pdc.controller;

import com.eystar.ext.kit.ContainerKit;
import com.eystar.ext.kit.page.PageKit;
import com.eystar.ext.route.ControllerBind;
import com.eystar.pdc.aop.auth.AuthAnno;
import com.eystar.pdc.aop.auth.AuthAnno.AuthType;
import com.eystar.pdc.aop.log.LogAnno;
import com.eystar.pdc.aop.log.LogAnno.LogType;
import com.eystar.pdc.model.DicItem;
import com.jfinal.plugin.activerecord.Page;

import cn.hutool.core.util.StrUtil;

/**
 * DicItem 管理 
 * @author Zhangjian
 *
 */
@ControllerBind(controllerKey="/item", viewPath="/pdc")
@AuthAnno(type = AuthType.Super, res = "dic")
public class DicItemController extends BaseController {

	/**
	 * 分页查找
	 * @throws Exception
	 */
	@AuthAnno(auth="look")
	@LogAnno(desc = "查看字典项列表", type = LogType.SEARCH)
	public void page() throws Exception{
		Page<DicItem> page = DicItem.dao.paginate(getAttr("PageOrder"), getModel(DicItem.class,"item"));
		renderJson(PageKit.toJSON(page));
	}
	
	/**
	 * 跳转到添加页面
	 * @throws Exception
	 */
	@AuthAnno(auth="save")
	public void add() throws Exception{
		render("dic_item_form.html");
	}
	
	/**
	 * 点击保存按钮
	 * @throws Exception
	 */
	@AuthAnno(auth="save")
	@LogAnno(desc = "添加字典项${item.item_value}", type = LogType.SAVE)
	public void save() throws Exception{
		DicItem dicItem = null;
		try {
			dicItem = getSaveModel(DicItem.class,"item");
			if (StrUtil.isBlank(dicItem.getStr("memo"))) {
				dicItem.set("memo", dicItem.getStr("item_value"));
			}
			dicItem.save();
			// 更新字典内存中的信息
			ContainerKit.remove("dic");
			renderJson(ok());
		} catch (Exception e) {
			logger.error("保存出错！" + dicItem.toJson(), e);
			renderJson(fail());
		}
	}

	/**
	 * 跳转到修改页面
	 * @throws Exception
	 */
	@AuthAnno(auth="update")
	public void edit() throws Exception{
		setAttr("item", DicItem.dao.findById(getPara()));
		render("dic_item_form.html");
	}
	
	/**
	 * 点击修改按钮
	 * @throws Exception
	 */
	@AuthAnno(auth="update")
	@LogAnno(desc = "修改字典项${item.item_value}", type = LogType.UPDATE)
	public void update() throws Exception{
		DicItem dicItem = null;
		try {
			dicItem = getUpdateModel(DicItem.class,"item");
			dicItem.update();
			// 更新字典内存中的信息
			ContainerKit.remove("dic");
			renderJson(ok());
		} catch (Exception e) {
			logger.error("修改出错！" + dicItem.toJson(), e);
			renderJson(fail());
		}
	}
	
	/**
	 * 支持多个删除，以英文逗号隔开
	 * @throws Exception
	 */
	@AuthAnno(auth="delete")
	@LogAnno(desc = "删除字典项", type = LogType.DELETE)
	public void delete() throws Exception{
		DicItem.dao.deleteByIds(getPara("ids"));
		renderJson(ok());
	}
	
	/**
	 * 检查某个字典是否存在字典项，不存在返回正常，存在返回失败
	 * @throws Exception
	 */
	public void check() throws Exception{
		DicItem dicItem = DicItem.dao.findFirstByColumnSecurity("dic_id", getPara());
		if (dicItem == null) {
			renderJson(ok());
		}else {
			renderJson(fail());
		}
	}
}